<template>
  <div class="product-list-container list-container" v-loading.fullscreen.lock="loading" >
    <div id="product-catalog-list"></div>
    <div ref="tableHeaderContainer" class="product-list-search-group-container bg-w list-search-group-container">
      <!-- 搜索 -->
      <div class="task-list-header-seach">
        <form class="task-flex task-ai" onsubmit="return false;">
          <div class="base-search-group input-with-append-search task-flex task-ai">
            <el-input
              v-model="searchModel.keyWord"
              :placeholder="$t('product.productType.placeholder.keyWord')"
              class="task-with-input task-mr12">
              <i slot="prefix" class="el-input__icon el-icon-search"></i>

              <el-button
                type="primary"
                slot="append"
                @click="searchModel.pageNum = 1; search(); trackEventHandler('search');"
                v-track="$track.formatParams('KEYWORD_SEARCH')"
                native-type="submit">
                {{$t('common.base.search')}}
              </el-button>
            </el-input>
            <el-button type="plain-third" @click="resetParams" v-track="$track.formatParams('RESET_SEARCH')">{{$t('common.base.reset')}}</el-button>
          </div>

          <div id="product-product-list-2"
               :class="['advanced-search-visible-btn', 'bg-w']"
               @click.self.stop="panelSearchAdvancedToggle">
            <i class="iconfont icon-filter"></i>
            {{$t('component.advancedSearch.title')}}
          </div>
        </form>
      </div>
    </div>

    <div class="product-list-section list-section">
      <!--operation bar start-->
      <div ref="tableDoContainer" class="operation-bar-container">
        <div class="top-btn-group flex-x product-btn-group">
          <el-button type="primary"
                        @click="goToCreate"
                        v-track="$track.formatParams('TO_CREATE')"
                        v-if="createdPermission"><i class="iconfont icon-add2"></i>{{$t('product.productType.btns.btn1')}}</el-button>
          <el-button
            type="primary"
            @click="createDirectory"
            v-track="$track.formatParams('CREATE_PRODUCT_CATALOG')"
            v-if="createdPermission">
            <i class="iconfont icon-add2"></i>
            {{$t('product.productType.createProductMenu')}}
          </el-button>
          <el-button type="plain-third" @click="openDialog('edit')" v-if="allowEditAllProduct" v-track="$track.formatParams('BATCH_EDIT')">
            <i class="iconfont icon-edit-square" ></i>{{$t('product.productType.btns.btn3')}}
          </el-button>
          <el-button
            type="plain-third"
            @click="delOpen"
            v-track="$track.formatParams('DELETE')"
            v-if="deletePermission">
            <i class="iconfont icon-delete"></i>{{$t('product.productType.btns.btn4')}}
          </el-button>
        </div>

        <div class="action-button-group flex-x bg-w" id="product-catalog-list-2">
          <!-- <el-button type="plain" @click="openDialog('sendMessage')" v-if="editedPermission === 3">发送短信</el-button> -->
          <!-- <el-button
            type="plain"
            @click="openDialog('edit')"
            v-if="editedPermission === 3"
          >批量编辑</el-button
          > -->
          <!-- <el-button type="plain" @click="openDialog('remind')" v-if="editedPermission === 3 && isShowCustomerRemind">批量提醒</el-button> -->
          <el-dropdown v-if="exportPermission && isButtonDisplayed">
            <div class="task-ai task-flex task-font14 task-c6 cur-point"
                 @click="trackEventHandler('moreAction')">
              <span class="task-mr4">{{$t('common.base.moreOperator')}}</span>
              <i class="iconfont icon-fdn-select task-icon"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="isButtonDisplayed && !isExperienceEdition && canProductCatalogImport">
                <div @click="openDialog('importProduct')" v-track="$track.formatParams('IMPORT_PRODUCT_TYPE', null, 'MORE_ACTIONS')">{{$t('product.productType.importProductType')}}</div>
              </el-dropdown-item>
              
              <el-dropdown-item v-if="isButtonDisplayed && canProductCatalogExport">
                <div @click="exportProduct(false)" v-track="$track.formatParams('EXPORT', null, 'MORE_ACTIONS')">{{ $t('common.base.export') }}</div>
              </el-dropdown-item >
              
              <el-dropdown-item v-if="isButtonDisplayed && canProductCatalogExport">
                <div @click="exportProduct(true)" v-track="$track.formatParams('EXPORT_ALL', null, 'MORE_ACTIONS')">{{ $t('common.base.exportAll') }}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <!-- 选择列 -->
          <div class="guide-box">
            <div :class="[
                   'task-ai',
                   'task-flex',
                   'task-font14',
                   'task-c6',
                   'cur-point',
                   'task-width103',
                 ]"
                v-track="$track.formatParams('SELECT_COLUMN')"
                @click="showAdvancedSetting">
              <span class="task-mr4">{{$t('common.base.choiceCol')}}</span>
              <i class="iconfont icon-fdn-select task-icon"></i>
            </div>
          </div>
        </div>
      </div>

      <!-- <div ref="BaseSelectionBarComponent" class="base-selection-wrapper">
        <base-selection-bar ref="baseSelectionBar"
                            v-model="multipleSelection"
                            @toggle-selection="toggleSelection"
                            @show-panel="() => (multipleSelectionPanelShow = true)" />
      </div> -->
      <div id="product-catalog-list-1" class="pad-l-16 pad-r-16 bg-w">
        <el-table
          stripe
          :data="page.list || []"
                     :highlight-current-row="false"
                     :key="tableKey"
                     :border="true"
                     @select="handleSelection"
                     @select-all="handleSelection"
                     @sort-change="sortChange"
                     @header-dragend="headerDragend"
                     :class="['task-list-table', 'common-list-table', 'bbx-normal-list-box']"
                     header-row-class-name="common-list-table-header taks-list-table-header"
                     :height="tableContainerHeight"
                     ref="multipleTable">
          <template slot="empty">
            <BaseListForNoData v-show="!loading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
          </template>
          <el-table-column type="selection"
                              width="48"
                              fixed="left"></el-table-column>
          <template v-for="(column, index) in columns">
            <el-table-column v-if="column.show"
                                :key="`${column.field}_${index}`"
                                :label="column.label"
                                :prop="column.field"
                                :width="column.width"
                                :class-name="
                                  column.field == 'name' ? 'product-name-superscript-td' : ''
                                "
                                :min-width="column.minWidth || '120px'"
                                :sortable="column.sortable"
                                :show-overflow-tooltip="getProductTypeListShowTooltip(column)"
                                :fixed="column.fixLeft || false"
                                :align="column.align">
              <template slot-scope="scope">

                <!--start 产品类型编号 -->
                <template v-if="column.fieldName === 'catalogName'">
                  <div :class="globalIsHaveProductCatalogViewDetailAuth ? 'link' : ''" @click="openProductMenuTab(scope.row.id)">
                    {{ scope.row[column.field] || '' }}
                  </div>
                </template>
                <!--end 产品类型编号 -->

                <!--start 关联服务项目 -->
                <template v-else-if="column.fieldName === 'relatedServiceItem'">
                  <div>
                    {{ scope.row[column.field] | fmtRelatedServiceItem }}
                  </div>
                </template>
                <!--end 关联服务项目 -->

                <template v-else-if="column.fieldName === 'pathName'">
                  {{ (scope.row[column.field] && scope.row[column.field].replace(new RegExp("/","g") ,' / ')) || '' }}
                </template>

                <template v-else-if="column.fieldName === 'productVideo'">
                  <template v-if="scope.row.productVideo && scope.row.productVideo.length">
                    <div class="link" @click="previewVideo(scope.row.productVideo[0].url)">
                      {{$t('common.base.preview')}}
                    </div>
                  </template>
                </template>

                <template v-else-if="column.field === 'tags'">
                  {{ scope.row | formatTags }}
                </template>
                <template v-else-if="column.formType === 'cascader'">
                  {{ scope.row.attribute[column.field] | displayCascader }}
                </template>
                <template v-else-if="column.formType === 'select' && !column.isSystem">
                  {{scope.row.attribute[column.field] | displaySelect}}
                </template>

                <template v-else-if="column.formType === 'user' && scope.row.attribute[column.field]">
                  <template v-if="isOpenData">
                    <template v-if="Array.isArray(scope.row.attribute[column.field])">
                      <open-data 
                        v-for="item in scope.row.attribute[column.field]" 
                        :key="item.staffId"
                        type='userName' 
                        :openid="item.staffId"
                      >
                      </open-data>
                    </template>
                    <template v-else>
                      <open-data type='userName' :openid="scope.row.attribute[column.field].staffId"></open-data>
                    </template>
                  </template>
                  <template v-else>
                    {{ getUserName(column, scope.row.attribute[column.field]) }}
                  </template>        
                  
                </template>
                <template v-else-if="column.formType == 'related_task'">
                  {{ getRelatedTask(scope.row.attribute[column.field]) }}
                </template>
                <template v-else-if="column.field === 'updateTime'">
                  <template v-if="scope.row.latesetUpdateRecord && !isOpenData">
                    <el-tooltip class="item"
                                   effect="dark"
                                   :content="scope.row.latesetUpdateRecord"
                                   placement="top-start">
                      <div @mouseover="showLatestUpdateRecord(scope.row)">
                        {{ scope.row.updateTime | formatDate }}
                      </div>
                    </el-tooltip>
                  </template>
                  <template v-else>
                    <div @mouseover="showLatestUpdateRecord(scope.row)">
                      {{ scope.row.updateTime | formatDate }}
                    </div>
                  </template>
                </template>
                <template v-else-if="column.field === 'createUser'">
                  <template v-if="isOpenData && scope.row.createUser">
                    <open-data type='userName' :openid="scope.row.createUser.staffId"></open-data>
                  </template>
                  <template v-else>
                    {{ scope.row.createUser && scope.row.createUser.displayName }}
                  </template>
                </template>
                <template v-else-if="column.field === 'createTime'">
                  {{ scope.row.createTime | formatDate }}
                </template>
                <div v-else-if="
                       column.formType === 'textarea' && column.isSystem != 1
                     "
                     v-html="buildTextarea(scope.row.attribute[column.field])"
                     @click="openOutsideLink"></div>

                <template v-else-if="column.formType == 'address' && column.isSystem != 1">
                  {{ getAddress(scope.row.attribute[column.field]) }}
                </template>
                <!-- 富文本 -->
                <template v-else-if="column.formType === 'richtext'">
                  <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
                    <span v-if="scope.row.attribute && scope.row.attribute[column.field]">{{$t('common.base.view')}}</span>
                  </div>
                </template>
                <template v-else-if="!column.isSystem">
                  {{ scope.row.attribute && scope.row.attribute[column.field] }}
                </template>

                <template v-else-if="column.fieldName == 'catalogId'">
                  {{ scope.row.pathName }}
                </template>
                <template v-else-if="column.fieldName === 'productPic'">
                  <div class="flex-x goods-img-list"
                       v-if="scope.row.productPic"
                       style="height:100%">
                    <template v-for="(item, index) in scope.row.productPic">
                      <img :key="index"
                           v-if="index <= 4"
                           class="cur-point mar-r-8"
                           :src="
                             item.url
                               ? `${item.url}?x-oss-process=image/resize,m_fill,h_32,w_32`
                               : defaultImg
                           "
                           @click.stop="previewImg(item.url,scope.row.productPic)" />
                    </template>
                    <div>
                      {{
                        scope.row[column.field].length > 5
                          ? `+${scope.row[column.field].length - 5}`
                          : ''
                      }}
                    </div>
                  </div>
                </template>
                <!-- <template v-else-if="column.fieldName == 'productNum'">
                  {{ scope.row['remind'] || '' }}
                </template> -->

                <template v-else-if="column.fieldName === 'thumbnail'">
                  <div
                    class="flex-x goods-img-list"
                    style="height:100%">
                    <template v-for="(item, index) in scope.row.thumbnail">
                      <img :key="index"
                           v-if="index==0"
                           class="cur-point"
                           :src="
                             item.url
                               ? `${item.url}?x-oss-process=image/resize,m_fill,h_32,w_32`
                               : defaultImg
                           "
                           @click.stop="previewImg(item.url,scope.row.thumbnail)" />
                    </template>
                  </div>
                </template>
                <template v-else-if="column.fieldName === 'productRelateMateriel'">
                  <div class="link" @click="jumpMaterial(scope.row.simpleMaterielVo)">
                    {{ scope.row.simpleMaterielVo &&  scope.row.simpleMaterielVo.materielName }}
                  </div>
                </template>
                <template v-else>
                  {{ formatFormQualityRule(column, scope.row) }}
                </template>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer-10">
        <div class="list-info">
          <i18n path="common.base.table.totalCount">
            <span place="count" class="level-padding">{{ page.total }}</span>
          </i18n>
          <template v-if="multipleSelection&&multipleSelection.length>0">
            <i18n path="common.base.table.selectedNth">
              <span place="count" class="product-selected-count" @click="multipleSelectionPanelShow = true">{{ multipleSelection.length }}</span>
            </i18n>
            <span class="product-selected-count" @click="toggleSelection()">{{$t('common.base.clear')}}</span>
          </template>
        </div>
        <el-pagination class="product-table-pagination"
                          background
                          @current-change="jump"
                          @size-change="handleSizeChange"
                          :page-sizes="defaultTableData.defaultPageSizes"
                          :page-size="page.pageSize"
                          :current-page="page.pageNum"
                          layout="prev, pager, next, sizes, jumper"
                          :total="page.total">
        </el-pagination>
      </div>
    </div>

    <base-panel class="product-panel"
                :show.sync="multipleSelectionPanelShow"
                width="420px">
      <h3 slot="title">
        <span>{{$t('product.productType.tips.tip1')}}({{ multipleSelection.length }})</span>
        <i v-if="multipleSelection.length"
           class="iconfont icon-qingkongshanchu product-panel-btn"
           @click="toggleSelection()"
           :title="$t('product.productType.tips.tip2')"
           data-placement="right"
           v-tooltip></i>
      </h3>

      <div class="product-selected-panel">
        <div class="product-selected-tip"
             v-if="!multipleSelection.length">
          <img :src="noDataImage" />
          <p>{{$t('product.productType.tips.tip2')}}</p>
        </div>
        <template v-else>
          <div class="product-selected-list">
            <div class="product-selected-row product-selected-head">
              <span class="product-selected-sn">{{ $t('common.base.productType') }}</span>
            </div>
            <div class="product-selected-row"
                 v-for="c in multipleSelection"
                 :key="c.id">
              <span class="product-selected-sn overHideCon-1">{{
                c.pathName
              }}</span>
              <button type="button"
                      class="product-selected-delete"
                      @click="removeFromSelection(c)">
                <i class="iconfont icon-fe-close"></i>
              </button>
            </div>
          </div>
        </template>
      </div>
    </base-panel>

    <biz-batch-edit ref="batchEditingDialog"
                    :config="{ fields: productTypeBatchEditFields, productTypes: productTypes }"
                    :callback="search"
                    :selected-ids="selectedIds"></biz-batch-edit>

    <biz-batch-remind ref="batchRemindingDialog" :selected-ids="selectedIds"></biz-batch-remind>

    <base-import :title="$t('product.productType.importProductType')"
                 ref="importProductModal"
                 @success="baseImportSuccess(), search()"
                 :action="productMenuListImport">
      <div slot="tip">
        <div class="base-import-warn">
          <p>
            <i18n path="common.base.importModal.downloadTemplateTip" tag="span">
              <a place="link" :href="productMenuListImportTem">{{$t('common.base.importModal.importTemplate')}}</a>
            </i18n>
          </p>
          <!--<p>导入产品前，请确保产品所属客户已存在。您可以 <a href="/customer/import/getAllCustomerId">点这里</a>导出包含所有已存在客户的模板</p>-->
        </div>
      </div>
    </base-import>

    <base-export ref="exportPanel"
                 :storage-key="exportStorageKey"
                 :columns="exportColumns"
                 :build-params="buildExportParams"
                 :validate="checkExportCount"
                 method="post"
                 :action="productMenuListExport" />

    <!-- <biz-batch-update
      ref="batchUpdateDialog"
      :selected-ids="selectedIds"
      :total-items="page.total"
      :build-download-params="buildParams"
      @success="search"
      action="/excels/customer/customerProductUpdateBatch"
    ></biz-batch-update> -->

    <!-- start 选择列设置 -->
    <biz-select-column ref="advanced" mode="catalog" @save="saveColumnStatus" />
    <!-- <base-table-advanced-setting ref="advanced" @save="modifyColumnStatus" /> -->

    <search-panel :init-data="initData"
                  :config="{
                    fields: this.productTypeSearchFields,
                  }"
                  ref="searchPanel">
      <div class="advanced-search-btn-group"
           slot="footer">
        <el-button type="plain-third"
                      v-track="$track.formatParams('RESET_SEARCH')"
                      @click="resetParams">{{$t('common.base.reset')}}</el-button>
        <el-button type="primary"
                      @click="powerfulSearch"
                      v-track="$track.formatParams('ADVANCED_SEARCH')"
                      native-type="submit">{{$t('common.base.search')}}</el-button>
      </div>
    </search-panel>
    <directory-dialog ref="directoryDialog"></directory-dialog>
    <!--查看富文本 -->
    <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
  </div>
</template>

<script>
// 产品类型列表
import { isOpenData, openAccurateTab } from '@src/util/platform'
import _ from 'lodash';
import { checkButtonDisplayed } from '@src/util/dom';
import { getSortableMinWidth, defaultTableData } from '@src/util/table';

import Page from '@model/Page';
import { safeNewDate } from '@src/util/time';
import SearchPanel from '@src/modules/productV2/productMenuList/compoment/SearchPanel.vue';
import directoryDialog from './compoment/directoryDialog.vue';

import { getUpdateRecord } from '@src/api/ProductApi';

import { catalogFieldFix } from '@src/modules/productV2/public.js';
import {
  getPageList,
  getProductMenuField,
  delTreeList,
} from '@src/api/ProductV2Api';
import TeamMixin from '@src/mixins/teamMixin';

/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import VersionMixin from '@src/mixins/versionMixin/index.ts'
import { VersionControlCustomerMixin } from '@src/mixins/versionControlMixin'
/* service */
import { getProductTypeBatchEditFields } from '@service/ProductTypeService.ts'
import { smoothQualityRuleField } from '@service/QualityRuleService.ts'
/* filter */
import { fmt_form_quality_rule } from '@src/filter/form'

import AuthMixin from '@src/mixins/authMixin'

/* export & import */
import { productMenuListExport } from '@src/api/Export';
import { productMenuListImport, productMenuListImportTem } from '@src/api/Import';
import { formatDate, useFormTimezone } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import StorageKeyEnum from '@model/enum/StorageKeyEnum'

const link_reg = /((((https?|ftp?):(?:\/\/)?)(?:[-;:&=\+\$]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\?\+=&;:%!\/@.\w_]*)#?(?:[-\+=&;%!\?\/@.\w_]*))?)/g;
import { getSystemNormalSearchInputForLength } from '@model/utils/getSystemConfig.ts'
import { getOssUrl } from '@src/util/assets'
const noDataImage = getOssUrl('/no_data.png')
import { formatAddress } from 'pub-bbx-utils';

export default {
  name: 'product-list',
  mixins: [
    TeamMixin, 
    ThemeMixin, 
    VersionMixin, 
    AuthMixin,
    VersionControlCustomerMixin
  ],
  props: {
    initData: {
      type: Object,
      default: () => ({}),
    },
  },
  data () {
    return {
      defaultTableData,
      noDataImage,
      exportStorageKey: StorageKeyEnum.ProductTypeExport,
      isButtonDisplayed: checkButtonDisplayed(),
      isOpenData,
      multipleSelectionPanelShow: false,
      page: new Page(),
      columns: [],
      multipleSelection: [],
      columnNum: 1,
      loading: true,
      selectedLimit: 500,
      searchIncludeMoreConditions: false,
      searchModel: {
        keyWord: '',
        pageSize: 10,
        pageNum: 1,
        orderDetail: {},
        moreConditions: {
          conditions: [],
        },
      },

      dynamicFields: [],
      filterTeams: [],
      tableKey: (Math.random() * 1000) >> 2,
      productTypeBatchEditFields: [],
      productTypeSearchFields: [],
      productMenuListExport,
      productMenuListImport,
      productMenuListImportTem,
      tableContainerHeight:'440px',
    };
  },
  computed: {
    auth () {
      return this.initData?.auths
    },
    allowEditAllProduct() {
      // 编辑按钮权限
      return this.editedPermission == 3
    },
    editedPermission () {
      return this.auth?.PRODUCT_CATALOG_EDIT;
    },
    createdPermission () {
      // 新建按钮权限
      return this.auth?.PRODUCT_CATALOG_CREATE;
    },
    viewedPermission () {
      return this.auth.CUSTOMER_VIEW === 3;
    },
    deletePermission () {
      // 删除按钮权限
      return this.auth.PRODUCT_CATALOG_DELETE === 3 && this.auth.PRODUCT_CATALOG_DELETE;
    },
    exportPermission () {
      return this.canProductCatalogImport || this.canProductCatalogExport
    },
    canProductCatalogImport() {
      return this.auth?.PRODUCT_CATALOG_IMPORT && this.createdPermission
    },
    canProductCatalogExport() {
      return this.auth?.PRODUCT_CATALOG_EXPORT
    },
    productFields () {
      return this.dynamicFields
        .concat(catalogFieldFix)
        .filter(
          (f) =>
            f.formType !== 'separator'
            && f.formType !== 'info'
            && f.formType !== 'autograph'
            && f.formType !== 'materialsBill'
            && ( ( f.fieldName == 'productVideo' || f.fieldName == 'productPic' || f.fieldName == 'thumbnail' ) ? true : f.formType !== 'attachment')
        )
        .map((f) => {
          if (f.isSystem == 1) {
            f.show = true;
          }
          return f;
        })
    },
    productTypes () {
      return this?.initData?.productConfig?.productType || [];
    },
    panelWidth () {
      return `${420 * this.columnNum}px`;
    },
    selectedIds () {
      return this.multipleSelection.map((p) => p.id);
    },
    exportColumns () {
      return [...this.columns].map((field) => {
        if (
          ['customer', 'productTemplate', 'remindCount'].some(
            (key) => key === field.fieldName
          )
          || field.formType === 'info' || field.formType === 'attachment'
        ) {
          field.export = false;
        } else {
          field.export = true;
        }

        return field;
      });
    },
    isShowCustomerRemind () {
      return this._isShowCustomerRemind
    }
  },
  watch: {
    productFields(newValue) {
      this.productTypeBatchEditFields = getProductTypeBatchEditFields(newValue)
      this.productTypeSearchFields = smoothQualityRuleField(newValue)
    }
  },
  filters: {
    formatTags ({ customer }) {
      if (!customer) return '';
      if (!customer.tags || !customer.tags.length) return '';
      return customer.tags.map((t) => t.tagName).join(' ');
    },
    formatDate (val) {
      if (!val) return '';
      return formatDate(val, 'YYYY-MM-DD HH:mm:ss');
    },
    displaySelect (value) {
      if (!value) return null;
      if (value && typeof value === 'string') {
        return value;
      }
      if (Array.isArray(value) && value.length) {
        return value.join('，');
      }
      return null;
    },
    displayCascader (value) {
      if (!value) return null;
      if (value && typeof value === 'string') {
        return value;
      }
      if (Array.isArray(value) && value.length) {
        return value.join('/');
      }
      return null;
    },
    fmtRelatedServiceItem(value) {
      return Array.isArray(value) ? value.map(item => item.name).join('，') : '';
    }
  },
  async mounted () {
    this.resetPage();

    // [tab_spec]标准化刷新方式
    window.__exports__refresh = this.resetPage;

    // this.$nextTick(() => {
    //   if (storageGet(PRODUCT_CATALOG_LIST) && storageGet(PRODUCT_CATALOG_LIST) > 0) this.$Guide().destroy('product-catalog-list')
    //   else this.$Guide([{
    //     content:
    //       '产品类型列表，可拖拽改变列表宽',
    //     haveStep: true,
    //     nowStep: 1,
    //     id: 'product-catalog-list',
    //     domObj:()=>{
    //       return document.getElementById('product-catalog-list-1').getElementsByClassName('el-table__header-wrapper')[0]
    //     },
    //     needCover: true,
    //     finishBtn: 'ok',
    //   }, {
    //     content:
    //       '选择自定义列展示、数据导出等功能',
    //     haveStep: true,
    //     nowStep: 2,
    //     id: 'product-catalog-list',
    //     domId: 'product-catalog-list-2',
    //     needCover: true,
    //     finishBtn: 'ok',
    //   }], 0, '', (e) => {
    //     return new Promise((resolve, reject) => {
    //       resolve()
    //     })
    //   }).create().then(res_=>{if(res_)storageSet(PRODUCT_CATALOG_LIST, '1')})
    // })
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight()
      }, 500)
    })

  },
  beforeDestroy () {
  },
  methods: {
    /** 打开富文本弹窗 */
    openRichtextVisible(row, column) {
      const richtextId = row?.attribute?.[column.fieldName] || ''
      this.$refs?.baseViewRichTextRef?.openDialog(richtextId)
    },
    // 跳转物料详情
    jumpMaterial(row) {
      openAccurateTab({
        type: PageRoutesTypeEnum.PageItemsDetail,
        key: row.materielId,
        params: `id=${row.materielId}`,
      });
    },
    // 新建产品目录
    createDirectory(){
      this.$refs.directoryDialog.open();
    },
    async resetPage () {
      // 获取产品动态字段
      try {
        let res = await getProductMenuField();
        this.dynamicFields = (res.result || []).filter(field => !(field.isHidden == 1 || field.isVisible == false));
        this.buildColumns();
      } catch (error) {
        this.buildColumns();
        console.error('product-list fetch product fields error', error);
      }
      this.revertStorage();
      this.search();

      if (!this.viewedPermission) {
        this.filterTeams = this.matchTags(this.teamsWithChildTag.slice());
      }
    },
    getAddress (field) {
      return formatAddress(field)
    },
    getRelatedTask (field) {
      return Array.isArray(field)
        ? field.map((item) => item.taskNo).join(',')
        : '';
    },
    // 处理人员显示
    getUserName (field, value) {
      // 多选
      if (Array.isArray(value)) {
        return value.map((i) => i.displayName || i.name).join(',');
      }

      let user = value || {};
      return user.displayName || user.name;
    },
    openOutsideLink (e) {
      let url = e.target.getAttribute('url');
      if (!url) return;
      if (!/http/gi.test(url))
        return this.$platform.alert(this.$t('common.base.tip.outsideLinkTip'));
      this.$platform.openLink(url);
    },
    buildTextarea (value) {
      return value
        ? value.replace(link_reg, (match) => {
          return `<a href="javascript:;" target="_blank" url="${match}">${match}</a>`;
        })
        : '';
    },
    powerfulSearch () {
      this.searchModel.pageNum = 1;
      this.searchModel.moreConditions = this.$refs.searchPanel.buildParams();

      this.search();
    },
    formatCustomizeAddress (ad) {
      return formatAddress(ad)
    },
    // 选择列 s

    /**
     * @description 表头更改
     */
    headerDragend (newWidth, oldWidth, column, event) {
      let data = this.columns
        .map((item) => {
          if (item.displayName === column.label) {
            item.width = column.width;
          }
          return item;
        })
        .map((item) => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },

    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus (event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach((col) => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },
    showAdvancedSetting () {
      window.TDAPP.onEvent('pc：产品类型管理-选择列事件');
      this.$refs.advanced.open(this.columns);
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus (event) {
      let columns = event.data || [];

      this.columns = [];

      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.saveSuccess'));
    },

    saveColumnStatusToStorage () {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map((c) => ({
        field: c.field,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },

    // 选择列 e

    openProductMenuTab (id) {
      
      if (!this.globalIsHaveProductCatalogViewDetailAuth) return 
      
      let fromId;
      try {
        fromId = window.frameElement.getAttribute('id');
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductV2CatalogView,
        key: id,
        params: `id=${id}`,
        fromId
      })
    },
    search () {
      const params = this.buildParams();
      
      this.loading = true;
      return getPageList(params)
        .then((res) => {
          this.loading = false;
          res.result.list = disposeFormListViewTime((res?.result?.list || []).map((item) => {
            item.attribute = item.attribute || {};
            item.productDesc = item.productDesc || '';
            item['catalogName'] = item.catalogName || '';
            return item;
          }), this.columns)
          this.page = Page.as(Object.freeze(res.result));
          this.matchSelected();
        })
        .catch((e) => console.error('fetch product catch an error', e));
    },
    buildParams () {
      const sm = Object.assign({}, this.searchModel);
      let params = {
        keyWord: getSystemNormalSearchInputForLength(sm.keyWord),
        pageSize: sm.pageSize,
        pageNum: sm.pageNum,
      };

      if (Object.keys(sm.orderDetail || {}).length) {
        params.orderDetail = sm.orderDetail;
      }

      if (
        Object.keys(sm.moreConditions).length > 1
        || sm.moreConditions.conditions.length
      ) {
        params = {
          ...params,
          ...sm.moreConditions,
        };
      }

      return params;
    },
    jump (pageNum) {
      this.searchModel.pageNum = pageNum;
      this.search();
    },
    resetParams () {
      window.TDAPP.onEvent('pc：产品管理-重置事件');
      this.searchIncludeMoreConditions = false;
      this.searchModel = {
        keyWord: '',
        pageNum: 1,
        pageSize: this.page.pageSize,
        orderDetail: {},
        moreConditions: {
          conditions: [],
        },
      };

      this.$refs.searchPanel.resetParams();
      this.search();
    },
    openDialog (action) {
      // if (action === 'sendMessage') {
      //   window.TDAPP.onEvent('pc：产品管理-发送短信事件');
      //   this.$refs.messageDialog.openSendMessageDialog();
      // }

      if (action === 'edit') {
        this.$refs.batchEditingDialog.open(true);
        window.TDAPP.onEvent('批量编辑	pc：产品类型管理-批量编辑事件');
      }

      // if (action === 'remind') {
      //   window.TDAPP.onEvent('批量提醒	pc：产品类型管理-批量提醒事件');
      //   this.$refs.batchRemindingDialog.openBatchRemindingDialog();
      // }

      if (action === 'importProduct') {
        this.$refs.importProductModal.open();
      }

      if (action === 'update') {
        // if (!this.multipleSelection || !this.multipleSelection.length) {
        //   return this.$platform.alert('您尚未选择数据，请选择数据后点击批量更新');
        // }
        this.$refs.batchUpdateDialog.openBatchUpdateCustomerDialog();
      }
    },
    delOpen(){
      window.TDAPP.onEvent('pc：产品类型管理-删除事件');
      if (!this.multipleSelection.length) {
        return this.$platform.alert(this.$t('product.productType.tips.tip4'));
      }
      const h = this.$createElement;
      this.$msgbox({
        title: this.$t('common.base.delete'),
        message:h('div', null, [
          h('p', this.$t('product.productType.tips.tip5', {selectNum: this.multipleSelection.length})),
          h('p', {style:'color:#FAAE14;'}, this.$t('product.productType.tips.tip6'))
        ]),
        showCancelButton: true,
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        beforeClose:(action, instance, done)=>{
          if(action === 'confirm') this.deleteProducts();
          done();
        }
      })
    },
    // operation
    async deleteProducts () {
      try {
        const ids = this.multipleSelection.map((p) => p.id);
        this.loading = true;
        const res = await delTreeList({ ids });
        this.loading = false;

        if (!res || res.code != 0)
          return this.$platform.notification({
            title: this.$t('common.base.fail'),
            type: 'error',
            message: res.message || this.$t('product.tips.unknownError'),
          });
        this.$platform.notification({
          title: this.$t('common.base.deleteSuccess'),
          type: 'success',
        });
        this.toggleSelection();
        window.parent.flashSomePage([{
          type: 'productV2_catalog_edit',
        }]);
        this.search();
      } catch (e) {
        this.loading = false;
        console.error('e', e);
      }
    },
    // 批量添加提醒成功后，更新产品的提醒数量
    updateProductRemindCount () {
      let count = 0;
      this.page.list = this.page.list.map((product) => {
        count = product.attribute.remindCount || 0;

        if (this.selectedIds.some((id) => id === product.id)) {
          product.attribute.remindCount = count + 1;
        }

        return product;
      });

      this.matchSelected();
    },
    // table method
    handleSelection (selection) {
      let tv = this.selectionCompute(selection);

      let original = this.multipleSelection.filter((ms) =>
        this.page.list.some((cs) => cs.id === ms.id)
      );

      let unSelected = this.page.list.filter((c) =>
        original.every((oc) => oc.id !== c.id)
      );

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach((row) => {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(this.$t('common.base.tip.choiceLimit', {limit: this.selectedLimit}));
      }

      this.multipleSelection = tv;

      this.$refs.baseSelectionBar?.openTooltip();
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
    // 计算已选择
    selectionCompute (selection) {
      let tv = [];

      tv = this.multipleSelection.filter((ms) =>
        this.page.list.every((c) => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    sortChange (option) {
      try {
        const { prop, order } = option;
        if (!order) {
          this.searchModel.orderDetail = {};
          return this.search();
        }
        const sortedField = this.productFields.filter((sf) => sf.fieldName === prop)[0] || {};

        let isSystem = sortedField.isSystem || 0;

        let sortProps = {
          catalogNum: 'catalog_num',
          createTime: 'create_time',
        }

        let sortModel = {
          isSystem,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          column: sortProps[prop] || prop,
        };

        if (sortProps[prop]) {
          sortProps[prop]
        }

        if (
          prop === 'createTime'
          || prop === 'updateTime'
          || sortedField.formType === 'date'
          || sortedField.formType === 'datetime'
        ) {
          sortModel.type = 'date';
        } else {
          sortModel.type = sortedField.formType;
        }

        this.searchModel.orderDetail = sortModel;

        this.search();
      } catch (e) {
        console.error('e', e);
      }
    },
    handleSizeChange (pageSize) {
      this.saveDataToStorage('pageSize', pageSize);
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.search();
    },
    toggleSelection (rows) {
      let isNotOnCurrentPage = false;
      let item = undefined;
      let row = undefined;

      if (rows) {
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.page.list.every((item) => {
            return item.id !== row.id;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },

    removeFromSelection (c) {
      if (!c || !c.id) return;

      this.multipleSelection = this.multipleSelection.filter(
        (ms) => ms.id !== c.id
      );
      this.multipleSelection.length < 1
        ? this.toggleSelection()
        : this.toggleSelection([c]);
    },
    // modifyColumnStatus(event) {
    //   let columns = event.data || [];
    //   let colMap = columns.reduce(
    //     (acc, col) => (acc[col.field] = col) && acc,
    //     {}
    //   );

    //   this.columns.forEach((col) => {
    //     let newCol = colMap[col.field];
    //     if (null != newCol) {
    //       this.$set(col, 'show', newCol.show);
    //       this.$set(col, 'width', newCol.width);
    //     }
    //   });

    //   const columnsStatus = this.columns.map((c) => ({
    //     field: c.field,
    //     show: c.show,
    //     width: c.width,
    //   }));
    //   this.saveDataToStorage('columnStatus', columnsStatus);
    // },
    buildColumns () {
      const localStorageData = this.getLocalStorageData();

      let columnStatus = localStorageData.columnStatus || [];
      let localColumns = columnStatus
        .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col) => (acc[col.field] = col) && acc, {});

      let fields;
      let productFields = smoothQualityRuleField(this.productFields)
      
      if(columnStatus.length){
        fields = [];
        columnStatus.forEach(item=>{
          const field = productFields.find(p=>p.fieldName === item.field);
          field && fields.push(field);
        });
        const extra = productFields.filter(item=>!columnStatus.find(c=>c.field === item.fieldName));
        fields.push(...extra);
      }else{
        fields = this.productFields;
        const thumbnail = fields.find(item => item.fieldName === 'thumbnail');
        if(thumbnail) thumbnail.show = false;
      }
      
      this.columns = fields
        .filter(
          (f) =>
            ( ( f.fieldName == 'productVideo' || f.fieldName == 'productPic' || f.fieldName == 'thumbnail' ) ? true : f.formType !== 'attachment')
            && f.formType !== 'separator'
            && f.formType !== 'info'
            && f.formType !== 'autograph'
            && f.formType !== 'materialsBill'
        )
        .map((field) => {
          let sortable = false;
          let minWidth = null;

          if (['date', 'datetime', 'number'].indexOf(field.formType) >= 0) {
            sortable = 'custom';
            minWidth = 100;
          }

          if (['type', 'catalogNum'].includes(field.fieldName)) {
            sortable = 'custom';
          }

          if (field.displayName.length > 4) {
            minWidth = field.displayName.length * 20;
          }

          if (sortable && field.displayName.length >= 4) {
            minWidth = getSortableMinWidth(field)
          }

          if (
            field.formType === 'datetime'
            || field.fieldName === 'updateTime'
            || field.fieldName === 'createTime'
          ) {
            minWidth = Math.max(150, minWidth);
          }

          return {
            ...field,
            label: field.displayName,
            field: field.fieldName,
            formType: field.formType,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            sortable,
            isSystem: field.isSystem,
          };
        })
        .map((col) => {
          let show = col.show === true;
          let { width } = col;
          let localField = localColumns[col.field];
          let fixLeft = localField?.fixLeft || null;
          if (null != localField) {
            width = typeof localField.width == 'number'
              ? `${localField.width}px`
              : '';
            show = localField.show !== false;
          }

          col.show = show;
          if(col.fieldName == 'pathName' && !width) width = '200px';
          if(col.fieldName == 'productNum' && !width) width = '120px';
          if(col.fieldName == 'createTime' && !width) width = '160px';
          col.width = width;
          col.type = 'column';
          col['fixLeft'] = fixLeft && 'left'
          return col;
        });
        console.log('this.columnsthis.columns',this.columns)
    },

    buildExportParams (checkedArr, ids) {
      let exportAll = !ids || !ids.length;
      let exportSearchModel = exportAll
        ? {
          ...this.buildParams(),
          exportTotal: this.page.total,
        }
        : { exportTotal: ids.length };
      let arr = [];
      checkedArr.forEach(item=>{
        arr.push(item);
      })
      let index = arr.findIndex(item=>item === 'createUser');
      if(index > -1){
        arr[index] = 'createUserName'
      }
      return {
        catalogChecked: this.exportData(arr).join(','),
        ids: exportAll ? '' : ids.join(','),
        exportSearchModel: JSON.stringify(exportSearchModel),
      };
    },
    /**
     * 导出数据对比
     */
     exportData(list = []) {
      return this.exportColumns.map(v => {
        let bool = list.some(item => {
          if (v.exportAlias) {
            return v.exportAlias === item
          }
          return v.fieldName === item

        })
        if (bool) {
          return v.exportAlias ? v.exportAlias : v.fieldName
        }
      }).filter(item => {
        return item
      })
    },
    /** 检测导出条数 */
    checkExportCount (ids, max) {
      let exportAll = !ids || !ids.length;
      return exportAll && this.page.total > max
        ? this.$t('common.base.tip.exportLimit', { max })
        : null;
    },

    exportProduct (exportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}${this.$t('product.productType.text.text1')}.xlsx`;
      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(this.$t('common.base.tip.exportUnChooseTip'));
        ids = this.selectedIds;
      }
      this.$refs.exportPanel.open(ids, fileName);
    },
    showLatestUpdateRecord (row) {
      if (row.latesetUpdateRecord) return;
      getUpdateRecord({
        productId: row.id,
      })
        .then((res) => {
          if (!res || res.status) return;

          this.page.list = this.page.list.map((c) => {
            if (c.id === row.id) {
              c.latesetUpdateRecord = res.data;
            }
            return c;
          });

          this.matchSelected();
        })
        .catch((e) => console.error('e', e));
    },

    createCustomerTab (productId) {
      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: productId,
        params: 'noHistory=1',
        fromId
      })
    },

    goToCreate () {
      window.TDAPP.onEvent('pc：产品类型管理-新建事件');
      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductCatalogCreate,
        fromId
      })
    },
    getLocalStorageData () {
      const dataStr = localStorage.getItem('productV2_product_menu_list') || '{}';
      return JSON.parse(dataStr);
    },
    saveDataToStorage (key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      localStorage.setItem('productV2_product_menu_list', JSON.stringify(data));
    },
    revertStorage () {
      const { pageSize, column_number } = this.getLocalStorageData();
      if (pageSize) {
        this.searchModel.pageSize = pageSize;
      }
      if (column_number) this.columnNum = Number(column_number);
    },
    // 匹配选中的列
    matchSelected () {
      if (!this.multipleSelection.length) return;

      const selected = this.page.list.filter((c) => {
        if (this.multipleSelection.some((sc) => sc.id === c.id)) {
          this.multipleSelection = this.multipleSelection.filter(
            (sc) => sc.id !== c.id
          );
          this.multipleSelection.push(c);
          return c;
        }
      }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },
    // 获取团队列表
    getTeamList (params) {
      return this.getBizTeamList(
        params,
        this.filterTeams,
        this.viewedPermission
      );
    },
    panelSearchAdvancedToggle () {
      window.TDAPP.onEvent('pc：产品类型管理-高级搜索事件');
      this.$refs.searchPanel.open();
      this.$nextTick(() => {
        let forms = document.getElementsByClassName('advanced-search-form');
        for (let i = 0; i < forms.length; i++) {
          let form = forms[i];
          form.setAttribute('novalidate', true);
        }
      });
    },
    // TalkingData事件埋点
    trackEventHandler (type) {
      if (type === 'search') {
        window.TDAPP.onEvent('pc：产品类型管理-搜索事件');
        return;
      }
      if (type === 'moreAction') {
        window.TDAPP.onEvent('pc：产品类型管理-更多操作事件');
        return;
      }
    },
    getRowKey (row) {
      return row.id || '';
    },
    previewImg (url, urls = []) {
      // this.$previewImg(url);
      if(typeof urls !== 'object'){
        urls = []
      }
      this.$previewElementImg(url, urls);
    },
    baseImportSuccess () {
      window.parent.flashSomePage([{
        type: 'productV2_catalog_edit',
      }]);
    },
    previewVideo (e) {
      this.$previewVideo(e);
    },
    formatFormQualityRule(column, row) {
      return fmt_form_quality_rule(column, row)
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
		 knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 24 - 12;
        console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        console.log(min, 'min')
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
  },
  components: {
    SearchPanel,
    [SearchPanel.name]: SearchPanel,
    [directoryDialog.name]:directoryDialog,
  },
};
</script>

<style lang="scss">

html,
body {
  height: 100%;
}
.product-list-container {
  height: 100%;
  padding: 10px;
  overflow: auto;
}

.product-columns-dropdown-menu {
  max-height: 300px;
  overflow: auto;
  .el-dropdown-menu__item {
    padding: 0;
  }
  .el-checkbox {
    width: 100%;
    padding: 5px 15px;
    margin: 0;
  }
}

// search
.product-list-container .product-list-search-group-container {
  border-radius: 4px;
  // padding: 16px;
  .base-search {
    background: #fff;
    border-radius: 3px;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    padding: 12px 10px;

    .product-list-base-search-group {
      display: flex;
      width: 440px;
      justify-content: space-between;

      .el-input {
        width: 300px;
        input {
          height: 31px;
          line-height: 31px;
          width: 300px;
        }
      }

      a {
        line-height: 33px;
      }
    }
  }
}

.product-list-container .product-list-section {
  margin-top: 12px;
  padding-top: 0;
}

// operation
.product-list-container .product-list-section .operation-bar-container {
  background: #fff;
  border-radius: 4px 4px 0 0;
  display: flex;
  justify-content: space-between;
  padding: 16px 16px 0 16px;

  .top-btn-group .base-button {
    margin-right: 5px;
  }

  .action-button-group {
    .base-button {
      margin-left: 5px;
    }
  }

  .el-dropdown-btn {
    padding: 0 15px;
    line-height: 31px;
    display: inline-block;
    background: $color-primary-light-9;
    color: $text-color-primary;
    outline: none;
    margin-left: 5px;
    .iconfont {
      margin-left: 5px;
      font-size: 12px;
    }

    &:hover {
      cursor: pointer;
      color: #fff;
      background: $color-primary;
    }
  }
}

// table

.el-table {
  border: none;
}

.el-table--small th,
.el-table--small td {
  height: 40px;
  padding: 3px 0;
}

.product-list-container .product-table {
  padding: 10px;

  &:before {
    height: 0;
  }

  .goods-img-list {
    img {
      width: 32px;
      height: 32px;
      margin-right: 4px;
      cursor: pointer;
    }
  }

  .product-table-header th {
    background: #f5f5f5;
    color: $text-color-primary;
    font-weight: normal;
  }

  th {
    color: #606266;
    font-size: 14px;
  }
  td {
    color: #909399;
    font-size: 13px;
    height: 40px;
  }

  .view-detail-btn {
    @include fontColor();
  }

  .select-column .el-checkbox {
    position: relative;
    top: 3px;
  }
}

.product-list-container .table-footer {
  display: flex;
  justify-content: space-between;
  padding: 0px 10px 10px 10px;
  background: #fff;
  border-radius: 0 0 3px 3px;

  .list-info {
    font-size: 13px;
    line-height: 32px;
    margin: 0;
    color: #767e89;

    .iconfont {
      position: relative;
      top: 1px;
    }

    .product-selected-count {
      @include fontColor();
      padding: 0 3px;
      width: 15px;
      text-align: center;
      cursor: pointer;
      font-size: 13px;
    }
  }

  .el-pagination__jump {
    margin-left: 0;
  }
}

// select panel
.product-list-container .product-selected-panel {
  font-size: 14px;
  height: calc(100% - 51px);

  .product-selected-tip {
    padding-top: 80px;

    img {
      display: block;
      width: 160px;
      margin: 0 auto;
    }

    p {
      text-align: center;
      color: $text-color-regular;
      margin: 8px 0 0 0;
      line-height: 20px;
    }
  }

  .product-selected-list {
    height: 100%;
    padding: 10px;
    overflow-y: auto;

    .product-selected-row {
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      border-bottom: 1px solid #ebeef5;
      font-size: 13px;

      &:hover {
        background-color: #f5f7fa;

        .product-selected-delete {
          visibility: visible;
        }
      }
    }

    .product-selected-head {
      background-color: #f0f5f5;
      color: #333;
      font-size: 14px;
    }

    .product-selected-sn {
      padding-left: 10px;
      width: 100%;
      @include text-ellipsis;
    }

    .product-selected-name {
      padding-left: 10px;
      flex: 1;
      @include text-ellipsis;
    }

    .product-selected-delete {
      width: 36px;
    }

    .product-selected-row button.product-selected-delete {
      padding: 0;
      width: 36px;
      height: 36px;
      border: none;
      background-color: transparent;
      outline: none;
      color: #646b78;
      visibility: hidden;

      i {
        font-size: 14px;
      }

      &:hover {
        color: #e84040;
      }
    }
  }
}

// advanced search form

.base-import-warn {
  p {
    margin: 0;
  }
}

// superscript
.product-name-superscript-td {
  padding: 0 !important;
  & > div {
    height: 31px;
    line-height: 31px !important;
    a {
      display: inline-block;
      height: 31px;
      line-height: 31px;
    }
  }
}

.product-panel {
  .base-panel-title {
    h3 {
      display: flex;
      justify-content: space-between;
    }
    .product-panel-btn {
      cursor: pointer;
      &:hover {
        @include fontColor();
      }
    }
  }
}
.el-table .cell {
  line-height: 31px;
}
//el-message-box 不是一个组件
.el-message-box__header{
    font-size: 18px;
    color: #262626;
    font-weight: 600;
    background-color: #fafafa;
    display: flex;
    align-items: center;
    padding: 10px 15px 10px 15px;
    min-height: 44px;
   .el-message-box__headerbtn{
      display:flex;
      align-items: center;
    }
  } 

  .flex-x{
    .cell{
      display:flex !important;
      justify-content:center;
    }
  }
</style>


<style lang="scss" scoped>
.link {
  color: $color-primary;
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
}
.common-list-table {
  ::v-deep .el-table__body {
    width: 100%;
    table-layout: fixed !important;
  }
}
::v-deep .el-table__body-wrapper{
  overflow-x: auto;
}

.task-list {
  &-header {
    background: #ffffff;
    box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.06);
    margin-bottom: 12px;
    border-top: none;

    &-seach {
      width: 100%;
      .seach {
        justify-content: space-between;
      }

      .advanced-search-visible-btn {
        // width: 98px;
        height: 32px;
        border-radius: 4px;
        font-size: 14px;
        color: $color-primary-light-6;
        line-height: 32px;
        text-align: center;
        cursor: pointer;
        white-space: nowrap;
      }
      .task-with-input {
        width: 400px !important;
      }
    }

    &-nav {
      > div {
        position: relative;
        border-top: 1px solid #f5f5f5;
        .state {
          padding-top: 4px;
          padding-left: 11px;
          width: 90px;
          font-weight: 500;
          background-color: #fafafa;
        }
        .element-icon i {
          position: absolute;
          right: 12px;
          top: 6px;
        }
        .list {
          width: 90%;
          overflow: hidden;
          // height: 30px;
          .list-item {
            > div {
              padding-left: 11px;
              font-size: 13px;
              width: 130px;
              height: 30px;
              overflow-y: hidden;
              color: #808080;
              line-height: 30px;
              cursor: pointer;
              &:hover {
                color: #333;
              }
            }
          }
        }
      }
    }
  }
}
.task-list-header-seach form {
  justify-content: flex-end;
}
.product-btn-group .el-button{
  max-width: 200px;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>
<style lang="scss">
  @import "@src/assets/scss/common-list.scss";
</style>
